<template>
    <div :class="errorBorder ? 'borderRedCss' : 'normalInputCss'">
        <label :style="{width: ((curNumber + '').length * 5) + 'px',minWidth: __config__.numberType === 'percentage' ? '97%' : '100%',position: 'relative'}">
            <el-input
                :placeholder="placeholder"
                :maxlength="maxlength"
                v-model="curNumber"
                @focus="numberFocus"
                @input="numberChange"
                @blur="numberBlur"
                :disabled="disabled"
                :controls="false"
                :precision="__config__.decimalPlaces"
                :prefix-icon="$attrs['prefix-icon']"
                :suffix-icon='$attrs["suffix-icon"]'>
                <template slot="prepend" v-if='__slot__.prepend'>{{__slot__.prepend}}</template>
                <template slot="append" v-if='__slot__.append'>{{__slot__.append}}</template>
            </el-input>
            <span v-if="__config__.numberType === 'percentage'" style="position: absolute;right: 10px;">%</span>
        </label>
    </div>
</template>
<script>
export default {
    name: 'el-number',
    props: [ 'placeholder', '__slot__', '__config__', 'value', 'showWordLimit', 'maxlength','disabled'],
    data () {
        return {
            curNumber: undefined,
            errorBorder: false,
            isReg: false
        }
    },
    created () {
        /**
         *  numberType: 'number',  // 数字类型  (percentage  百分比类型)
            isDecimal: true, // 是否保留小数位数
            decimalPlaces: 0, // 保留的小数位数
            zeroPadding: false, // 是否补零
            rounding: false, // 是否四舍五入
            showThousands: false, // 是否显示千分符
        *
        */
        // 判断是否初始化存在千分符
        if (this.__config__.showThousands && this.value) {
            this.curNumber = this.thousandSplit(this.value)
        } else {
            if(this.value ==="" ||this.value ===null){
              this.curNumber = undefined
            }
            else if((Number(this.value).toString() !== "NaN"  && !this.__config__.zeroPadding) || (Number(this.value).toString() !== "NaN"  && this.__config__.zeroPadding && this.__config__.decimalPlaces  === 0)){
              this.curNumber = Number(this.value)
             
            }else if(Number(this.value).toString() !== "NaN"  && this.__config__.zeroPadding && this.__config__.decimalPlaces > 0) {//开启补零
                this.curNumber = this.value
            }else{
              this.curNumber = undefined
            }
        }
    },
    watch: {
        value (newVal) {
            if(this.isReg){
                this.curNumber = undefined
            }else{
                if (this.__config__.showThousands && ((newVal + '').trim()??'') !== '' && Number(this.value).toString() !== 'NaN' && Number(this.value).toString() !== 'undefined') {
                    this.curNumber = this.thousandSplit(newVal)
                } else {
                    if(this.value ==="" ||this.value ===null){
                    this.curNumber = undefined
                    }
                    else if((Number(this.value).toString() !== "NaN"  && !this.__config__.zeroPadding) || (Number(this.value).toString() !== "NaN"  && this.__config__.zeroPadding && this.__config__.decimalPlaces  === 0)){
                    this.curNumber = Number(this.value)
                    }else if(Number(this.value).toString() !== "NaN"  && this.__config__.zeroPadding && this.__config__.decimalPlaces > 0){ //开启补零 并且有小数位数
                        this.curNumber = this.value 
                    }else if(Number(this.value).toString() === 'NaN' || Number(this.value).toString() === 'undefined'){
                        this.curNumber = ''
                    }else{
                        this.curNumber = undefined
                    }
                }
            }
           
        },
        '__config__.numberType' () {
            this.watchChange()
        },
        '__config__.isDecimal' () {
            this.watchChange()
        },
        '__config__.decimalPlaces' () {
            this.watchChange()
        },
        '__config__.zeroPadding' () {
            this.watchChange()
        },
        '__config__.rounding' () {
            this.watchChange()
        },
        '__config__.showThousands' (newVal) {
            if (newVal) {
                this.watchChange()
            } else {
                this.numberFocus(this.curNumber)
            }
        },
    },
    methods: {
        watchChange () {
            if ((this.curNumber + '').trim()??'' !== '') {
                this.numberBlur(this.curNumber, 'watch')
            }
        },
        numberChange (value) {
            // let newVal = value + ''
            // if (newVal.indexOf('e') !== -1) {
            //     newVal = newVal.replaceAll('e', '')
            // } else if (newVal.startsWith('-') && newVal.indexOf('-') !== -1) {
            //     newVal = newVal.replaceAll('-', '')
            //     newVal = '-' + newVal
            // } else if (!newVal.startsWith('-') && newVal.indexOf('-') !== -1) {
            //     newVal = newVal.replaceAll('-', '')
            // } else if (newVal.split('.').length > 2) {
            //     newVal = newVal.substr(0, newVal.length - 1)
            // } else if (newVal.split('.').length > 2 && (newVal.startsWith('.') || newVal.endsWith('.'))) {
            //     newVal = newVal.replaceAll('.', '')
            // }
            // this.curNumber = Number(newVal)
        },
        numberBlur (e, flag = 'blur') {
            var reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");
            let pattern = /[a-zA-Z]/;
            if(reg.test(e.target.value) || pattern.test(e.target.value)){
                this.curNumber = undefined
                this.isReg = true
            }else{
                this.isReg = false
                console.log('eeee', e,flag)
                if (this.__config__.showThousands && this.curNumber) {
                    this.curNumber = this.thousandSplit(this.curNumber)
                }

                // 是否保留小数位数
                let newVal = ''
                if (flag !== 'blur') {
                    newVal = e
                } else {
                    newVal = e.target.value + ''
                }

                if (this.__config__.isDecimal && (this.curNumber + '' === '0' || this.curNumber)) {
                    // 是否四舍五入
                    if (this.__config__.rounding) {
                        newVal = this.round(Number(newVal), this.__config__.decimalPlaces)
                    }
                
                }
                if (this.__config__.required && !newVal) {
                    // this.errorBorder = true
                } else {
                    this.errorBorder = false
                }
            
                if(this.__config__.zeroPadding && this.__config__.decimalPlaces > 0){//开启是否补零 并且有小数位数
                    newVal += ''
                    const numList = newVal.split('.')
                    // 不存在小数点时
                    if (numList.length < 2) {
                        // 是否补零
                        if (this.__config__.zeroPadding && newVal) {
                            newVal = newVal + '.' + '0'.repeat(this.__config__.decimalPlaces)
                        }
                    } else {
                        // 存在小数点时
                        const secondNum = numList[1]
                        if (this.__config__.decimalPlaces !== 0 && secondNum.length > this.__config__.decimalPlaces) {
                            let newStr = ''
                            // 保留的位数
                            newStr = secondNum.substr(0, this.__config__.decimalPlaces)
                            newVal = secondNum[0] + '.' + newStr
                        }
                        // 是否补零
                        if (this.__config__.zeroPadding && newVal) {
                            newVal = newVal + '0'.repeat(this.__config__.decimalPlaces - secondNum.length)
                        }
                    }
                }
                if (newVal + '' !== '0' && newVal) {
                    this.curNumber = newVal
                } else {
                    this.curNumber = undefined
                }
            }
            this.$emit('input', this.curNumber)
        },
        // 焦点进入时去掉多余 , 符号
        numberFocus () {
            if (this.__config__.showThousands && this.curNumber) {
                if (this.curNumber + '' !== '0' && this.curNumber) {
                    this.curNumber = Number(this.curNumber.replaceAll(',', ''))
                } else {
                    this.curNumber = undefined
                }
            }
        },
        // 四舍五入(存在小数位)
        round(number, precision) {
            return Math.round(+number + 'e' + precision) / Math.pow(10, precision);
        },
        // 千分符
        thousandSplit(num) {
            var res=num.toString().replace(/\d+/, function(n){ // 先提取整数部分
                return n.replace(/(\d)(?=(\d{3})+$)/g,function($1){
                    return $1+",";
                    }); 
            })
            return res;
        },
        getNumber (param) {
            if (param??'' !== '') {
                let strParam = String(param)
                let flag = /e/.test(strParam)
                if (!flag) return param
                // 指数符号 true: 正，false: 负
                let sysbol = true
                if (/e-/.test(strParam)) {
                  sysbol = false
                }
                // 指数
                let index = Number(strParam.match(/\d+$/)[0])
                // 基数
                let basis = strParam.match(/^[\d\.]+/)[0].replace(/\./, '')
                if (sysbol) {
                  return basis.padEnd(index + 1, 0)
                } else {
                  return basis.padStart(index + basis.length, 0).replace(/^0/, '0.')
                }
            } else {
                return ''
            }
        },
    }
}
</script>
<style scoped lang="less">
// /deep/.el-input--medium .el-input__inner {
//     text-align: left;
// }
// /deep/.el-input-number--medium {
//     width: 100%;
//     line-height: 34px;
// }
// .borderRedCss{
//     display:flex;
//     width: 100%;
//     background-color: white;
//     border-radius: 5px;
//     border: 1px solid red;
// }
// .normalInputCss{
//     // display:flex;
//     width: 100%;
//     background-color: white;
//     border-radius: 5px;
//     border: 1px solid lightgrey;
// }
// /deep/input::-webkit-input-placeholder {
//        color: #C0C4CC;
//        font-weight: 400;
// }
// /deep/.el-input--medium .el-input__inner {
//     border: none;
//     font-weight: 400;
// }
// /deep/input::-webkit-outer-spin-button,
// /deep/input::-webkit-inner-spin-button{
//     -webkit-appearance: none !important;
//     margin: 0; 
// }
</style>